package org.train.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.train.dao.ChartDao;
import org.train.dao.ProjectDao;
import org.train.entity.ProjectPo;
import org.train.entity.RevenueExpenditurePo;
import org.train.util.AmountUtil;
import org.train.util.R;
import org.train.util.RUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ChartService{
    @Autowired
    private ChartDao chartDao;
    @Autowired
    private ProjectDao projectDao;

    public R pieData(){
        // 按照科室过滤project表，得到科室对应的ids
        // 由ids与revenue_expenditure表拼接，得到科室对应的收支信息
        Map<String, List<Map<String, Object>>> data = new HashMap<>();
        data.put("totalAmount", new ArrayList<>());
        data.put("totalBilling", new ArrayList<>());
        data.put("totalGrossProfit", new ArrayList<>());
        data.put("profitRate", new ArrayList<>());
        for(int i = 0; i < 5; ++i){
            // 计算科室累计合同额
            double totalAmount = 0.0;
            List<ProjectPo> pps = projectDao.selectList(new QueryWrapper<ProjectPo>()
                    .eq("research_office", i));
            for(ProjectPo e: pps){
                totalAmount += e.getContractAmount();
            }
            // 计算科室其他累计数据
            List<RevenueExpenditurePo> list = chartDao.queryAllRevenueExpendituresOfOneResearchOffice(i);
            AmountUtil.Amounts amounts = AmountUtil.calcAmounts(list, -1); // -1表示不关心年度

            // 准备结果结构
            data.get("totalAmount").add(buildPieceData(i,totalAmount));
            data.get("totalBilling").add(buildPieceData(i, amounts.totalBilling));

            data.get("totalGrossProfit").add(buildPieceData(i, amounts.totalGrossProfit()));
            data.get("profitRate").add(buildPieceData(i, amounts.profitRate()));
        }
        return RUtil.success(data);
    }

    // 构造pieData中的每个小项的结构{ researchOffice, value }
    private static Map<String, Object> buildPieceData(Integer researchOffice, Double value){
        Map<String, Object> map = new HashMap<>();
        map.put("researchOffice", researchOffice);
        map.put("value", value);
        return map;
    }
}

